﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Collections;
using System.Reflection;

namespace UtilityLibrary.Http
{
	public class CookieContainerModel : ICookieModel
	{
		private CookieContainer _cookieContainer;
		public CookieContainerModel()
		{
			_cookieContainer = new CookieContainer();
			_cookieContainer.MaxCookieSize = 100;
		}

		public void SetCookies(System.Net.HttpWebRequest request)
		{
			request.CookieContainer = _cookieContainer;
		}

		public void GetCookies(System.Net.HttpWebResponse response)
		{
		}

		public CookieCollection Cookies
		{
			get
			{
				return GetAllCookies(_cookieContainer);
			}
		}

		private CookieCollection GetAllCookies(CookieContainer cc)
		{
			CookieCollection lstCookies = new CookieCollection();

			Hashtable table = (Hashtable)cc.GetType().InvokeMember("m_domainTable",
			    BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance, null, cc, new object[] { });

			foreach (object pathList in table.Values)
			{
				SortedList lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list",
				    BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance, null, pathList, new object[] { });
				foreach (CookieCollection colCookies in lstCookieCol.Values)
				{
					foreach (Cookie c in colCookies)
					{
						lstCookies.Add(c);
					}
				}
			}

			return lstCookies;
		}
	}
}
